import { _decorator, Component, Node, Size, UITransform } from "cc";

const { ccclass, property } = _decorator;

@ccclass('AutoFitScole')
export class AutoFitScole extends Component {
    @property(UITransform)
    private parentTr: UITransform = null;

    @property({ tooltip: "Click to fit the node to parent size" })
    private _fitButton: boolean = false;

    @property({ serializable: true })
    set fitButton(value: boolean) {
        if (value) {
            this.resetFit();
            this._fitButton = false;
        }
    }

    get fitButton(): boolean {
        return this._fitButton;
    }

    @property
    private offsetScale: number = 0;

    onLoad() {
        if (!this.parentTr) {
            this.parentTr = this.node.parent.getComponent(UITransform);
        }
    }

    start() {
        this.scheduleOnce(() => {
            this.resetFit();
        }, 0); // Delay to ensure the parent size is correct
    }

    public resetFit(): void {
        let parentSize: Size = new Size(this.parentTr.width, this.parentTr.height);
        let selfSize: Size = new Size(this.node.getComponent(UITransform).width, this.node.getComponent(UITransform).height);

        let scaleX = parentSize.width / selfSize.width;
        let scaleY = parentSize.height / selfSize.height;
        let scale = Math.max(scaleX, scaleY); // Use the larger scale to ensure the node completely fills the parent
        this.node.setScale(scale + this.offsetScale, scale + this.offsetScale, 1);
    }
}